package com.fzkj.thread.maipaio;

import java.util.ArrayList;
import java.util.List;

public class MyThread implements Runnable {

    // 线程名称
    private String name;

    // 当前窗口卖的票集合
    private List<Integer> tikes;

    // 总的票
    private static Integer totalTickets = 50 ;

    public MyThread(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        tikes = new ArrayList<>();
        while(sell()){}
        // 打印
        print(tikes);
    }

    // 买票
    private boolean sell(){
        synchronized (MyThread.class) {
            try {
                if (totalTickets > 0){
                    System.out.println(name + "卖的" + totalTickets + "张票");
                    tikes.add(totalTickets);
                    totalTickets--;
                    Thread.sleep(200);
                    return true;
                } else {
                    return false;
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            return false;
        }
    }

    // 打印
    private void print(List<Integer> list){
        synchronized (MyThread.class) {
            System.out.print(name + "卖了： ");
//            list.forEach(System.out::print);
            for (Integer integer : list) {
                System.out.print(integer+" ");
            }
            System.out.println();
        }
    }
}
